import axios, { Axios } from 'axios'
import { AxiosResponse } from 'axios'
import { openStdin } from 'process'

interface Response {
  data: object
  msg: string
}

function prefixUrl(url: string) {
  if (!url.startsWith('http')) {
    let prefix: string = 'http://localhost:8080'
    if (!url.startsWith('/')) prefix += '/'
    url = prefix + url
  }
  return url
}

function handleResponse(response: AxiosResponse): Response {
  if (response.status >= 300 || response.status < 200) {
    throw new Error(response.statusText)
  } else if (response.data.success) {
    return {
      msg: response.data.message,
      data: response.data.object,
    }
  } else {
    throw new Error(response.data.message)
  }
}

async function post(url: string, data: any): Promise<Response> {
  url = prefixUrl(url)
  if (typeof data != 'object') {
    throw new Error(`post: data-${data} is not an object`)
  }
  let formData = new FormData()
  Object.keys(data).forEach((key) => {
    formData.append(key, data[key])
  })
  if (DEBUG) {
    console.log(`post to ${url}, data ${data}`)
  }
  let response = await axios.post(url, {
    data: formData,
  })
  return handleResponse(response)
}

interface GetOption {
  responseType?: 'blob'
}

async function get(
  url: string,
  query: any,
  option?: GetOption
): Promise<Response> {
  url = prefixUrl(url)
  if (typeof query != 'object') {
    query = {}
  }
  if (DEBUG) {
    console.log(`get to ${url}, query ${query}`)
  }
  let response = await axios.get(url, {
    params: query,
    responseType: option?.responseType,
  })
  return handleResponse(response)
}

export { post, get }
